<div class="lazy-image {fillFixSize ? 'lazy-image-fixed-size': ''}" style={computedStyle} >
  <img
    class="{fillFixSize ? 'fixed-size-img': ''}"
    aria-hidden={ariaHidden}
    {alt}
    {title}
    {width}
    {height}
    src={displaySrc}
    style={focusStyle}
    ref:node
  />
</div>
<style>
  .lazy-image {
    margin: 0;
    padding: 0;
    overflow: hidden;
    display: flex;
  }

  .fixed-size-img {
    width: 100%;
    height: 100%;
  }
  .lazy-image-fixed-size {
    position: absolute;
    width: 100%;
    height: 100%;
  }


</style>
<script>
  import { decodeImage } from '../_utils/decodeImage.js'
  import { coordsToPercent } from '../_utils/coordsToPercent.js'

  export default {
    async oncreate () {
      const { node } = this.refs
      try {
        await decodeImage(node)
      } catch (e) {
        console.error('Image decode error', node && node.src, e)
        this.set({ error: true })
      }
    },
    data: () => ({
      error: false,
      forceSize: false,
      fallback: undefined,
      focus: undefined,
      background: '',
      width: undefined,
      height: undefined,
      ariaHidden: false,
      alt: '',
      title: '',
      blurhash: undefined
    }),
    computed: {
      computedStyle: ({ background }) => {
        return [
          background && `background: ${background};`
        ].filter(Boolean).join('')
      },
      focusStyle: ({ focus }) => {
        // Here we do a pure css version instead of using
        // https://github.com/jonom/jquery-focuspoint#1-calculate-your-images-focus-point

        if (!focus) {
          return 'background-position: center;'
        }
        return `object-position: ${coordsToPercent(focus.x)}% ${100 - coordsToPercent(focus.y)}%;`
      },
      fillFixSize: ({ forceSize, $largeInlineMedia }) => !$largeInlineMedia && !forceSize,
      displaySrc: ({ blurhash, error, src, fallback }) => (blurhash || (error && fallback) || src)
    }
  }
</script>
